package my.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class XMLFileUtil {
	private static final Log log = LogFactory.getLog(XMLFileUtil.class);


	/**
	 * 保存为XML
	 * 
	 * @param viewer
	 * @param f
	 * @return
	 * /
	public static boolean saveXML(GraphicalViewer viewer, File f) {
		// 以下存储xml文件
		Document document = DocumentHelper.createDocument();
		Element logicDiagramElement = document.addElement("ubce");
		EditPart rep = viewer.getRootEditPart();
		List children = rep.getChildren();
		for (Object child : children) {
			if (child instanceof ContentsEditPart) {
				Element contentsModelElement = logicDiagramElement.addElement(IXMLModel.MULTI);
				ContentsEditPart contentsEditPart = (ContentsEditPart) child;
				List subChildren = contentsEditPart.getChildren();
				ContentsModel contentsModel = (ContentsModel) contentsEditPart.getModel();
				logicDiagramElement.addElement(IXMLModel.FORM_ID).addText(contentsModel.getFormId());
				logicDiagramElement.addElement(IXMLModel.FORM_NAME).addText(contentsModel.getFormName());
				logicDiagramElement.addElement(IXMLModel.FORMTYPE).addText(CommonEntity.I().getDict(DictType.FORMTYPE).getKeyByValue(contentsModel.getFormTypeName()));
				logicDiagramElement.addAttribute(IXMLModel.WSDL_URI, contentsModel.getWsdlURI());
				String objId = CollectionUtil.getObjIdByObjName(CommonEntity.I().getBizObjs(), contentsModel.getObjName());
				logicDiagramElement.addElement(IXMLModel.OBJID).addText( objId);
				for (Object subChild : subChildren) {
					XMLFactory.factory(subChild, contentsModelElement);
				}
			}
		}
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");// 设置XML文档的编码类型
			format.setExpandEmptyElements(true);
			format.setTrimText(false);//
			format.setIndent(true);// 设置是否缩进
			format.setIndent("\t");// 以空格方式实现缩进
			format.setNewlines(true); // 设置是否换行
			// IFile file = ((IFileEditorInput)getEditorInput()).getFile();
			// final IFile file = (IFile) ((DiagramEditorInput)getEditorInput()).getFile();
			// IFile file = ((IFileEditorInput) getEditorInput()).getFile();
			// File f = file.getLocation().toFile();
			// File f = ((DiagramEditorInput) getEditorInput()).getPath().toFile();
			XMLWriter output = new XMLWriter(new FileOutputStream(f), format);
			output.write(document);
			output.close();
			return true;
		} catch (IOException e) {
			log.error("============================保存文件出错",e);
		}
		return false;
	}

	public static String initEmptyDiagram(String formId, String formName, String wsdlURI) {
		Document document = DocumentHelper.createDocument();
		Element logicDiagramElement = document.addElement("ubce");
		logicDiagramElement.addElement(IXMLModel.FORM_ID, formId);
		logicDiagramElement.addElement(IXMLModel.FORM_NAME, formName);
		logicDiagramElement.addAttribute(IXMLModel.WSDL_URI, wsdlURI);
		log.debug("document:" + document.toString());
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");// 设置XML文档的编码类型
		format.setExpandEmptyElements(true);
		format.setTrimText(false);//
		format.setIndent(true);// 设置是否缩进
		format.setIndent("\t");// 以空格方式实现缩进
		format.setNewlines(true); // 设置是否换行
		try {
			String content = new XMLWriter(format).toString();
			log.debug(content);
			return content;
		} catch (IOException e) {
			log.error("初始化XML文件出错:", e);
		}
		return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	}

	/**
	 * 
	 * @param filePath
	 *            文件路径
	 * @return
	 */
	public static String getFileContent(File afile) {
		File file = afile;
		FileReader fr = null;
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		String tmpStr = "";
		if (file.exists()) {
			try {
				fr = new FileReader(file);
				reader = new BufferedReader(fr);
				while ((tmpStr = reader.readLine()) != null) {
					sb.append(tmpStr);
					sb.append(System.getProperty("line.separator"));
				}
				return new String(sb.toString().getBytes("GBK"), "UTF-8");
			} catch (FileNotFoundException e) {
				log.error("---文件未找到", e);
			} catch (IOException e) {
				log.error("---读取异常", e);
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						log.error("---reader关闭异常", e);
					}
				}
				if (fr != null) {
					try {
						fr.close();
					} catch (IOException e) {
						log.error("---filereader关闭异常", e);
					}
				}
			}
		}
		return null;
	}

	public static String getXMLFileContent(File file) {
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(file);
			return document.asXML();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getXMLFileContent(String filePath) {
		return getXMLFileContent(new File(filePath));
	}

	public static void save(Document document , File f){
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");// 设置XML文档的编码类型
			format.setExpandEmptyElements(true);
			format.setTrimText(false);//
			format.setIndent(true);// 设置是否缩进
			format.setIndent("\t");// 以空格方式实现缩进
			format.setNewlines(true); // 设置是否换行
			// IFile file = ((IFileEditorInput)getEditorInput()).getFile();
			// final IFile file = (IFile) ((DiagramEditorInput)getEditorInput()).getFile();
			// IFile file = ((IFileEditorInput) getEditorInput()).getFile();
			// File f = file.getLocation().toFile();
			// File f = ((DiagramEditorInput) getEditorInput()).getPath().toFile();
			XMLWriter output = new XMLWriter(new FileOutputStream(f), format);
			output.write(document);
			output.close();
		} catch (IOException e) {
			log.error("============================保存文件出错",e);
		}
	}
	
	
	public static Map<String, Object> XMLString2Map(String xmlString) {
		Document document;
		try {
			document = DocumentHelper.parseText(xmlString);
			return Dom2Map(document);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return new LinkedHashMap();
	}

	public static Map<String, Object> Dom2Map(Document doc) {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		if (doc == null)
			return map;
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			List list = e.elements();
			if (list.size() > 0) {
				map.put(e.getName(), Dom2Map(e));
			} else
				map.put(e.getName(), e.getText());
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public static Map Dom2Map(Element e) {
		Map map = new LinkedHashMap();
		List list = e.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					Map m = Dom2Map(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), m);
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.put(iter.getName(), mapList);
					} else
						map.put(iter.getName(), iter.getText());
				}
			}
		} else
			map.put(e.getName(), e.getText());
		return map;
	}

	public static String getFileContent(String filePath) {
		return getFileContent(new File(filePath));
	}

}
